package edu.ntu.im.p2ptrade;

import java.io.IOException;

import edu.ntu.im.p2ptrade.entity.Dialog;
import edu.ntu.im.p2ptrade.entity.DialogRepository;
import edu.ntu.im.p2ptrade.msg.AuthenticatedMessageWrapper;
import edu.ntu.im.p2ptrade.msg.GenericDialog;
import edu.ntu.im.p2ptrade.msg.PMessage;

import net.jxta.endpoint.ByteArrayMessageElement;
import net.jxta.endpoint.Message;

public class Util {

	public static void transdferMessageToPeer(Message msg, String peer) {
		try {
			
			DialogHost.getInstance().sendTo(msg, peer);
			
			if (msg.getMessageElement(P2PTrade.getInstance().getAppName(),
					AuthenticatedMessageWrapper.LOGMSG) != null) {
				String logmsg = msg.getMessageElement(
						P2PTrade.getInstance().getAppName(),
						AuthenticatedMessageWrapper.LOGMSG).toString();
				System.out.println("logmsg:" + logmsg);
				ByteArrayMessageElement bame = (ByteArrayMessageElement) msg
						.getMessageElement(P2PTrade.getInstance().getAppName(),
								AuthenticatedMessageWrapper.DIGITAL_SIGNATURE);
				byte[] ds = bame.getBytes(true);
				RecordManager.addRecord(logmsg, msg, P2PTrade.getInstance()
						.getPeerName(), peer, ds);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void talkToPeer(GenericDialog dialog, String peer) {
		PMessage authdialog = new AuthenticatedMessageWrapper(dialog);
		// DialogRepository.getInstance().addDialog(new Dialog(dialog, peer));
		try {
			transdferMessageToPeer(authdialog.getMessageToTransfer(), peer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String toNormalName(String advName) {
		if (advName.indexOf("@") >= 0) {
			return advName.substring(0, advName.indexOf("@"));
		}
		return advName;
	}

	public static String dumpBytes(byte[] bytes) {
		int i;
		StringBuffer sb = new StringBuffer();
		for (i = 0; i < bytes.length; i++) {
			if (i % 32 == 0 && i != 0) {
				sb.append(" \n ");
			}
			String s = Integer.toHexString(bytes[i]);
			if (s.length() < 2) {
				s = " 0 " + s;
			}
			if (s.length() > 2) {
				s = s.substring(s.length() - 2);
			}
			sb.append(s);
		}
		return sb.toString();
	}

}
